import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Tag,
  Notification
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import UserReset from './reset';
import { post, del } from '@/utils/request';
import PermissionWrapper from '@/components/PermissionWrapper';
import { confirmDelete } from '@/utils/util';


function SearchTable() {
  const t = useLocale(locale);
  const ref = useRef(null);
  const resetRef = useRef(null);

  const tableCallback = async (record, type) => {
    console.log(record)
    if('edit'===type){
      ref.current?.onAddEdit(record.id)
    }else if('delete'==type){
      confirmDelete('确定删除用户？',()=>{
        del('/api/user/' + record.id,{},{})
        .then(() => {
          Notification.info({content:'删除成功'})
          loadData();
        });
      })      
    }else if('reset'===type){
      resetRef.current?.reset(record.id,record.name);
    }
  };
  const columns = useMemo(() => getColumns(t, tableCallback), [t]);

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  useEffect(() => {
    loadData();
  }, [pagination.current, pagination.pageSize, formParams]);

  const loadData = () =>{
    const { current, pageSize } = pagination;
    setLoading(true);
    console.log('loading....')
    post('/api/user/list', {
          page: current,
          size: pageSize,
          ...formParams,
      })
      .then((res) => {
        if(res.data){
          setData(res.data);
          setPatination({
            ...pagination,
            current,
            pageSize,
            total: res.total,
          });
        }
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }
  function handleSubmit(value) {
    loadData();
  }

  return (
    <Card>
      <SearchForm ref={ref} onSearch={handleSearch} onSubmit={handleSubmit} />
      <UserReset ref={resetRef} />
      <Table
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />
    </Card>
  );
}
const lessPadding = {paddingLeft: 5, paddingRight:5 }

function getColumns(
  t: any,
  callback: (record: Record<string, any>, type: string) => Promise<void>
) {
  return [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (x) => {
        return <Tag color={x ? 'green' : 'grey'}>{ x ? '启用' : '禁用' }</Tag>;
      },
    },
    {
      title: t['action'],
      dataIndex: 'id',
      width:180,
      headerCellStyle: { paddingLeft: '15px' },
      render: (_, record) => (
        <>
        <PermissionWrapper requiredPermissions={[{ resource: 'menu.sys.user', actions: ['edit'] }]}>
          <Button
            type="text"
            size="small"
            style={lessPadding}
            onClick={() => callback(record, 'edit')}
          >
            {t['edit']}
          </Button>
        </PermissionWrapper>
        <PermissionWrapper requiredPermissions={[{ resource: 'menu.sys.user', actions: ['all'] }]}>
            <Button
              type="text"
              size="small"
              style={lessPadding}
              onClick={() => callback(record, 'reset')}
            >
              重置密码
            </Button>
            <Button
              type="text"
              size="small"
              style={lessPadding}
              onClick={() => callback(record, 'delete')}
            >
                {t['delete']}
            </Button>
          </PermissionWrapper>
        </>
      ),
    },
  ];
}
export default SearchTable;
